import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import datasets

iris = datasets.load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']

data = df.iloc[:, :-1].values
samples, features = df.shape
U, s, V = np.linalg.svd(data)
new_data = U[:, :2]
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
colors = ['r', 'g', 'b']
marks = ['o', '^', '+']
for i in range(samples):
    ax.scatter( new_data[i, 0], new_data[i, 1], c=colors[int(data[i, -1])],
               marker=marks[int(data[i, -1])] )
plt.xlabel('SVD1')
plt.ylabel('SVD2')
plt.show()

'''
实现过程：
1.使用前4列作为linalg.svd()的输入
2.得到左奇异矩阵U，奇异矩阵s，右奇异矩阵V
3.选择U中前两个特征分别作为二维平面的x,y进行可视化
'''